"""
获取当前的IP地址和地理位置信息
"""

import requests
import json
import socket

def get_local_ip():
    """获取本地IP地址"""
    try:
        # 创建一个临时socket连接，获取本地IP
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        local_ip = s.getsockname()[0]
        s.close()
        return local_ip
    except Exception as e:
        print(f"获取本地IP失败: {e}")
        return "未知"

def get_public_ip():
    """获取公网IP地址"""
    try:
        # 使用ipify API获取公网IP
        response = requests.get("https://api.ipify.org?format=json")
        if response.status_code == 200:
            return response.json()["ip"]
        else:
            # 备用服务
            response = requests.get("https://ipinfo.io/json")
            if response.status_code == 200:
                return response.json()["ip"]
            
        return "未能获取"
    except Exception as e:
        print(f"获取公网IP失败: {e}")
        return "未知"

def get_location_info(ip=None):
    """获取IP的地理位置信息"""
    try:
        if not ip:
            ip = get_public_ip()
            
        # 使用ipinfo.io获取地理位置信息
        response = requests.get(f"https://ipinfo.io/{ip}/json")
        if response.status_code == 200:
            location_data = response.json()
            return location_data
        
        # 备用服务
        response = requests.get(f"https://ipapi.co/{ip}/json/")
        if response.status_code == 200:
            return response.json()
        
        return {"error": "无法获取位置信息"}
    except Exception as e:
        print(f"获取位置信息失败: {e}")
        return {"error": str(e)}

def main():
    """主函数"""
    print("===== 当前网络位置信息 =====")
    
    # 获取本地IP
    local_ip = get_local_ip()
    print(f"本地IP地址: {local_ip}")
    
    # 获取公网IP
    public_ip = get_public_ip()
    print(f"公网IP地址: {public_ip}")
    
    # 获取地理位置信息
    print("\n正在获取地理位置信息...")
    location_info = get_location_info(public_ip)
    
    # 美化打印
    print("\n===== 详细地理位置信息 =====")
    for key, value in location_info.items():
        print(f"{key}: {value}")
    
    # 如果有城市和国家信息，单独打印
    if "city" in location_info and "country" in location_info:
        print(f"\n当前位置: {location_info.get('city', '未知城市')}, {location_info.get('country', '未知国家')}")
    
    # 检查是否在受限区域
    country = location_info.get("country", "").upper()
    restricted_regions = ["CN"] # 可能受限的区域代码
    
    if country in restricted_regions:
        print(f"\n⚠️ 警告: 当前位置 ({country}) 可能无法访问某些国际API服务 (如Google API)")
        print("建议: 考虑使用代理服务器或VPN来访问这些服务，或者使用其他支持当前地区的API替代方案")
    
if __name__ == "__main__":
    main() 